package inventory.utils;

import inventory.common.RoleLevelEnum;
import inventory.entity.po.UserPo;
import inventory.mappers.UserPoMapper;

import java.util.Map;

public class UserRoleUtil {

    /**
     * 根据userId，workId判断map里面的user是否为普通用户，不是的话做一定的处理;  优先使用userId
     * @param map
     */
    public static void judeUser(Map<String,Object> map){
        String userId = (String) map.get("user_id");
        String workId = (String) map.get("work_id");

        UserPoMapper userPoMapper = (UserPoMapper) SpringUtil.getBean("userPoMapper");

        UserPo userPoByUserId ;   //查询对应用户id 的用户
        UserPo userPoByWorkId ;   //查询对应workId的用户

        //如果userId不为空，则去根据userId查询
        if (userId != null && !userId.equals("")){
            userPoByUserId = userPoMapper.selectById(userId);

            if (userPoByUserId!=null && !userPoByUserId.getState().equals(RoleLevelEnum.PERSON.getCode())){
                map.remove("user_id");
                map.put("role_id", userPoByUserId.getRoleId());
            }

            map.remove("work_id");
            return;     //保证 根据userId或者 workId 二选一的查询

        }


        //如果workId不为空，则去根据workId查询
        if (workId!=null && !workId.equals("")){
            UserPo tempUserPo = new UserPo();       //临时对象，方便下面查询用
            tempUserPo.setWorkId(workId);
            userPoByWorkId = userPoMapper.selectOne(tempUserPo);

            if (userPoByWorkId!=null && !userPoByWorkId.getState().equals(RoleLevelEnum.PERSON.getCode())){
                map.remove("work_id");
                map.put("role_id", userPoByWorkId.getRoleId());
                map.remove("user_id");
            }else {
                map.remove("work_id");
                map.put("user_id", userPoByWorkId.getUserId());
            }




        }


    }
}
